package com.ai.aicodeinghelper.controller;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;

import java.io.IOException;
import java.time.Duration;
import java.util.Set;

@RestController
@RequestMapping("/demo-sse")
public class DemoSSE {

    @GetMapping(value = "/demo-flux",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<Long> demoFlux(){
        // 默认情况下，在不map的时候，postman 接受的content-type不是sse，所以我们需要手动更新 produces
        // take 代表只发送5个事件

        return Flux.interval(Duration.ofSeconds(1)).take(5)
                .concatWith(Flux.just(2003L));
    }


    @GetMapping("/demo-flux-sse")
    public Flux<ServerSentEvent<String>> demo(HttpServletResponse response){
        response.setCharacterEncoding("UTF-8");
        Flux<Long> interval = Flux.interval(Duration.ofSeconds(1));
        Flux<ServerSentEvent<String>> map = interval.map(chunk ->
                ServerSentEvent.<String>builder()
                .id("123123")
                .event("event")
                .data("SSE - " + chunk)
                .build()
        );
        return map;
    }

    @GetMapping("/sse_emitter")
    public SseEmitter sseEmitter(HttpServletResponse response)  {
        response.setCharacterEncoding("UTF-8");
        SseEmitter sseEmitter = new SseEmitter();

       new Thread(()->{
           for (int i = 0; i < 20; i++){
               try {
                   // 方式1
//                    sseEmitter.send("SSE - " + i);

                   // 方式2
                   Set<ResponseBodyEmitter.DataWithMediaType> build = SseEmitter.event()
                           .data("SSE - " + i)
                           .id("IDIDID")
                           .name("NAME")
                           .build();
                   sseEmitter.send(build);
               } catch (IOException e) {
                   sseEmitter.completeWithError(e); // sse 发送失败的处理
                   throw new RuntimeException(e);
               }
               try {
                   Thread.sleep(1000);
               } catch (InterruptedException e) {
                   sseEmitter.completeWithError(e);
                   throw new RuntimeException(e);
               }
           }
           sseEmitter.complete(); // sse 发送完成
       }).start();

        return sseEmitter;
    }

}
